package com.yunhe.sms.service;


import com.yunhe.commens.util.DaoFactory;
import com.yunhe.commens.util.MybatisUtils;
import com.yunhe.sms.dao.system.UserDao;
import com.yunhe.sms.dto.Menus;
import com.yunhe.sms.entity.system.Premission;
import com.yunhe.sms.entity.system.User;
import com.yunhe.sms.service.system.PremissionService;
import com.yunhe.sms.service.system.impl.PremissionServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LeiPeifeng
 * @version V1.0
 * @date 2017/10/17 0017 19:02
 * @Description: 登录服务
 */
@Service
public class Loginservice {
    @Autowired
    private PremissionService premissionService ;
    @Autowired
    private UserDao userDao;

    /**
     * 登录验证
     * @param user
     * @return
     */
    public  User login(User user) {
        User login = userDao.login ( user );
        return login;
    }

    /**
     * 左侧菜单树
     * @param rolId
     * @return
     */
    public   List<Menus> premirole(@Param ( "rolId" ) Long rolId) {
        List<Menus> menusList=new ArrayList<> ();//菜单树集合
        Map<Long, Menus> map = new HashMap<> ();
        List<Premission> modulepremi = premissionService.findPremi ( rolId, 1 );//查询当前角色的所有模块
        List<Premission> pagepremi = premissionService.findPremi ( rolId, 2 );//查询当前角色的所有页面

//        把所有的模块放入菜单树集合
        for (Premission p : modulepremi){
            Menus menus = new Menus ( p.getId (), p.getName (), p.getUrl () );
            menusList.add ( menus );
            map.put ( p.getId (), menus);//放入map是为了与页面进行匹配保存时的方便
        }
//        把所有的角色页面放入菜单树集合，且要与模块对应存放
        for (Premission p:pagepremi){
            Menus menus = new Menus ( p.getId (), p.getName (), p.getUrl () );
            Menus menus1 = map.get ( p.getParentsId () );//通过父级id获取模块的对象
            if (null != menus1){
                menus1.getMenusList().add ( menus );//把页面加入对应模块下的属相List<Menus>
            }
        }
        return  menusList;
    }

    /**
     * 把用户所有的权限放入map集合中，key为URL
     * @param rolId
     */
    public  Map<String,Premission> findAllpremiss(Long rolId){
        List<Premission> findrollpremi = premissionService.findrollpremi ( rolId );
        Map<String,Premission> map=new HashMap<> (  );
        for (Premission p : findrollpremi){
            map.put ( p.getUrl (),p );
        }
        return map;
    }


}
